package com.doublefish.doublefishrobot.ui.home.s8;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.adapter.ModeCustomListAdapter;
import com.doublefish.doublefishrobot.ui.home.bean.ModeSettingBean;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.MessageEvent;
import com.doublefish.doublefishrobot.utils.ble.DFS8ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;
import com.doublefish.doublefishrobot.utils.ble.bean.OnBleResponseHandler;
import com.doublefish.doublefishrobot.utils.db.DataBaseApi;
import com.doublefish.doublefishrobot.widget.CommonDialog;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/10/18 16:59
 */
public class S8ModeCustomListActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView titleTv;

    @BindView(R.id.tv_right)
    TextView rightTv;

    @BindView(R.id.tv_remote_0)
    TextView remoteTv0;
    @BindView(R.id.tv_remote_1)
    TextView remoteTv1;

    @BindView(R.id.recycler)
    SwipeRecyclerView recyclerView;

    @BindView(R.id.et_search)
    EditText editText;

    private ModeCustomListAdapter adapter;
    private List<ModeSettingBean> showBeanList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mode_custom_list_s8;
    }

    @Override
    protected void initView() {
        titleTv.setText(getString(R.string.custom));

        rightTv.setText("+");
        rightTv.setTextSize(28);
    }

    @Override
    protected void initData() {
        //向遥控器同步脚本
        syncRemoteModes();
        //获取本地自定义模式列表
        refreshCustomList();
    }

    @Override
    protected void initListener() {
        adapter = new ModeCustomListAdapter(this,showBeanList);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ModeSettingBean bean = showBeanList.get(position);
                toCustomActivity(bean, 0);
            }
        });
        //侧滑删除
        createSwipeMenu();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        //键盘搜索按钮点击的监听
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //回收键盘 并搜索
                    onSearchBtnClick();
                }
                return false;
            }
        });

        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    //创建侧滑菜单
    private void createSwipeMenu() {
        // 创建侧滑菜单
        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) {
                //删除菜单
                SwipeMenuItem deleteItem = new SwipeMenuItem(S8ModeCustomListActivity.this);
                deleteItem.setBackgroundColor(getResources().getColor(R.color.red));
                deleteItem.setText(getString(R.string.delete));
                deleteItem.setTextColor(getResources().getColor(R.color.white));
                deleteItem.setWidth(150);
                deleteItem.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);

                rightMenu.addMenuItem(deleteItem);
            }
        };
        recyclerView.setSwipeMenuCreator(mSwipeMenuCreator);
        recyclerView.setItemViewSwipeEnabled(false); //侧滑删除

        //菜单点击监听
        recyclerView.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge swipeMenuBridge, int i) {
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                swipeMenuBridge.closeMenu();

                ModeSettingBean bean = showBeanList.get(i);
                showDeleteAlertDialog(bean);
            }
        });
    }

    //向遥控器同步脚本
    private void syncRemoteModes() {
        remoteTv0.setText(AppCacheUtil.getInstance().getS8Bean0().getName());
        remoteTv1.setText(AppCacheUtil.getInstance().getS8Bean1().getName());

        if (AppCacheUtil.getInstance().isSynchronizedForRemote()) {
            return;
        }
        writeRemoteModes();
    }

    //写入脚本
    private void writeRemoteModes() {
        int dir = AppCacheUtil.getInstance().getRemoteModelDir();
        //目前固定写死2个脚本
        String fileName0 = AppCacheUtil.getInstance().remoteModelName(0);
        String script0 = AppCacheUtil.getInstance().getS8Bean0().getScript();
        DFS8ProtocolManager.getInstance().writeScript(dir, fileName0, script0, new OnBleResponseHandler() {
            @Override
            public boolean onResponse(boolean success, int status, Object res) {
               if (success) {
                   //第一条写入完成 继续写第二条
                   String fileName1 = AppCacheUtil.getInstance().remoteModelName(1);
                   String script1 =  AppCacheUtil.getInstance().getS8Bean1().getScript();
                   DFS8ProtocolManager.getInstance().writeScript(dir, fileName1, script1, new OnBleResponseHandler() {
                       @Override
                       public boolean onResponse(boolean success1, int status1, Object res1) {
                           if (success1) {
                               //第二条写入完成
                               AppCacheUtil.getInstance().setSynchronizedForRemote(true);
                           }
                           return false;
                       }
                   });
               }
                return false;
            }
        });
    }

    //从数据库读取自定义模式
    private void refreshCustomList() {
        String searchText = editText.getText().toString().trim();
        //	1.超8  2.超6  3.超5 4.超3
        DataBaseApi.queryCustomModelList(1, searchText, new DataBaseApi.OnQueryCustomModelListListner() {
            @Override
            public void onCallback(boolean suc, List<ModeSettingBean> list) {
                if (suc) {
                    showBeanList.clear();
                    if (list != null) {
                        showBeanList.addAll(list);
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    @OnClick(R.id.tv_right)
    public void onRightBtnClick() {
        //新增 初始化脚本
        String json = readCustomModeSettingFromFile();
        ModeSettingBean modeSettingBean = JSON.parseObject(json, ModeSettingBean.class);
        modeSettingBean.setProtocolType(ModeConstant.ProtocolTypeS8);
        //前往自定义界面
        toCustomActivity(modeSettingBean, 0);
    }

    //是否是 遥控器的自定义的模型，0不是， 1模型1， 2模型2。 默认0
    private void toCustomActivity(ModeSettingBean bean, int remoteModelType) {
        Intent intent = new Intent(this, S8ModeCustomActivity.class);
        intent.putExtra("mode", bean);
        intent.putExtra("remoteModelType", remoteModelType);
        startActivity(intent);
    }

    @OnClick(R.id.tv_search)
    public void onSearchBtnClick() {
        hideKeyboard();
        refreshCustomList();
    }

    @OnClick({R.id.ll_remote_0})
    public void onRemoteLayout0Click(View view) {
       toCustomActivity(AppCacheUtil.getInstance().getS8Bean0(), 1);
    }

    @OnClick({R.id.ll_remote_1})
    public void onRemoteLayout1Click(View view) {
        toCustomActivity(AppCacheUtil.getInstance().getS8Bean1(), 2);
    }

    private void showDeleteAlertDialog(ModeSettingBean bean) {
        CommonDialog commomDialog = new CommonDialog(this, getString(R.string.delete_custom_mode_alert), bean.getName(), new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    deleteSettingBean(bean);
                }
            }
        });
        commomDialog.show();
    }

    private void deleteSettingBean(ModeSettingBean bean) {
        DataBaseApi.deleteCustomModel(bean, new DataBaseApi.OnDatabaseCommonListner() {
            @Override
            public void onCallback(boolean suc) {
                if (suc) {
                    refreshCustomList();
                }
            }
        });
    }

    //回收键盘
    private void hideKeyboard() {
        //回收键盘
        InputMethodManager imManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imManager != null && getCurrentFocus() != null) {
            imManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    //从本地Assets中读取文件
    private String readCustomModeSettingFromFile() {
        try {
            InputStream inputStream = getResources().getAssets().open("s8_mode_cus.json");
            int length = inputStream.available();
            byte[] buff = new byte[length];
            inputStream.read(buff);
            inputStream.close();

            String json = new String(buff, StandardCharsets.UTF_8);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    //eventbus
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (MessageEvent.CUSTOM_MODE_CHANGED.equals(event.getTag())) {
            refreshCustomList();
        }
    }

    @OnClick(R.id.ll_back)
    public void onBackClick() {
        finish();
    }
}
